from django.shortcuts import render, get_object_or_404, redirect
from .forms import LoginForm, RegisterForm, ForgetPwdForm, ModifyPwdForm, UserForm, UserProfileForm
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from .models import EmailVerifyRecord
from django.contrib import messages
from django.contrib.auth.hashers import make_password
from utils.email_send import send_email
from django.urls import reverse
from .models import UserProfile
from blog.models import Post
from .forms import PostForm

def login_view(request):
    """登录功能"""
    if request.method != 'POST':
        form = LoginForm()
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                # 登录成功之后跳转到个人中心
                return redirect('users:user_profile')
            else:
                redirect_url = reverse('users:login')
                return render(request, 'users/redirect.html', {'message': '登录失败','redirect_url': redirect_url})

    context = {'form': form}
    return render(request, 'users/login.html',context)
        
def active_user(request, active_code):
    """ 激活用户账户 """
    try:
        # 假设每个激活码只对应一个记录，使用 get 而不是 filter
        record = EmailVerifyRecord.objects.get(code=active_code)
        # 获取关联的用户邮箱
        email = record.email
        # 获取用户对象
        user = User.objects.get(email=email)
        # 激活用户账户
        user.is_active = True
        user.save()  # 确保保存用户状态

        redirect_url = reverse('users:login')
        return render(request, 'users/redirect.html', {'message': '激活成功','redirect_url':redirect_url})

    except EmailVerifyRecord.DoesNotExist:
        # 如果没有找到记录，返回错误消息并重定向到登录页面
        return render(request, 'users/redirect.html', {
            'message': '激活链接无效或已过期，请重新注册。',
            'redirect_url': 'users:register'
        })

def register(request):
    """ 注册视图 """
    if request.method != 'POST':
        form = RegisterForm()
    else:
        form = RegisterForm(request.POST)
        if form.is_valid():
            new_user = form.save(commit=False)
            new_user.set_password(form.cleaned_data.get('password'))
            new_user.username = form.cleaned_data.get('email')
            new_user.is_active = False  # 设置用户未激活
            new_user.save()

            # 发送邮件
            send_email(form.cleaned_data.get('email'), 'register')

            messages.success(request, '注册邮件发送成功,请到邮箱点击链接激活账号！')
            return redirect('users:login')
            
    context = {'form': form}
    return render(request, 'users/register.html',context)

def forget_pwd(request):
    """ 填写邮箱地址发送邮件表单页面 """
    if request.method == 'GET':
        form = ForgetPwdForm()
    elif request.method == 'POST':
        form = ForgetPwdForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            exists = User.objects.filter(email=email).exists()  
            if exists:
                send_email(form.cleaned_data.get('email'), 'forget')
                redirect_url = reverse('users:login')
                return render(request, 'users/redirect.html', {'message': '邮件已经发送请查收！','redirect_url': redirect_url})
            else:
                redirect_url = reverse('users:register')
                return render(request, 'users/redirect.html', {'message': '邮箱还未注册，请前往注册！','redirect_url': redirect_url})
    
    return render(request, 'users/forget_pwd.html', {'form': form})


@login_required(login_url='users:login')
def user_profile(request):
    ''' 用户中心 '''
    user = User.objects.get(username=request.user)
    return render(request, 'users/user_profile.html', {'user': user})


def logout_view(request):
    ''' 登出 '''
    logout(request)
    return redirect('users:login')

def forget_pwd_url(request, active_code):
    """ 发送邮箱链接视图，并修改密码 """
    if request.method != 'POST':
        form = ModifyPwdForm()
    else:
        form = ModifyPwdForm(request.POST)
        if form.is_valid():
            record = EmailVerifyRecord.objects.get(code=active_code)
            email = record.email
            user = User.objects.get(email=email)
            user.username = email
            user.password = make_password(form.cleaned_data.get('password'))
            user.save()

            redirect_url = reverse('users:login')
            return render(request, 'users/redirect.html', {'message': '修改成功,请重新登录','redirect_url': redirect_url})
        else:
            redirect_url = reverse('users:forget_pwd')
            return render(request, 'users/redirect.html', {'message': '修改失败','redirect_url': redirect_url})

    return render(request, 'users/reset_pwd.html', {'form': form})


@login_required(login_url='users:login')
def editor_users(request):
    """ 编辑用户信息 """
    user = request.user
    try:
        user_profile = user.userprofile
    except UserProfile.DoesNotExist:
        user_profile = UserProfile(owner=user)

    if request.method == "POST":
        post_data = request.POST.copy()
        post_data['email'] = user.email
        form = UserForm(post_data, instance=user)
        user_profile_form = UserProfileForm(post_data, request.FILES, instance=user_profile)

        if form.is_valid() and user_profile_form.is_valid():
            form.save()
            user_profile_form.save()
            return redirect('users:user_profile')
        else:
            print(form.errors)
            print(user_profile_form.errors)
    else:
        form = UserForm(instance=user)
        user_profile_form = UserProfileForm(instance=user_profile)

    return render(request, 'users/editor_users.html', {
        'form': form,
        'user_profile_form': user_profile_form,
    })



@login_required(login_url='/login/')  # 确保用户登录，如果未登录则重定向到登录页面
def create_post(request):
    if request.method == 'POST':
        form = PostForm(request.POST)

        if form.is_valid():
            print('Form is valid:', form.is_valid())  # 打印表单验证结果
            post = form.save(commit=False)
            print('post before save:', post)  # 打印 post 对象状态
            post.owner = request.user  # 确保用户已登录并设置owner
            post.save()

            redirect_url = reverse('users:user_profile')
            return render(request, 'users/redirect.html', {'message': '发布成功','redirect_url': redirect_url})
        else:
            # 如果表单无效，打印错误信息
            print('Form errors:', form.errors)
            # 重新渲染表单页面，并传递错误信息
            return render(request, 'users/create_post.html', {'form': form})
    else:
        form = PostForm()
    return render(request, 'users/create_post.html', {'form': form})




@login_required
def delete_post(request, post_id):
    post = get_object_or_404(Post, id=post_id)
    if post.owner == request.user:
        post.delete()
        redirect_url = reverse('users:article_list')
        return render(request, 'users/redirect.html', {'message': '删除成功','redirect_url': redirect_url})
    else:
        redirect_url = reverse('users:article_list')
        return render(request, 'users/redirect.html', {'message': '删除失败','redirect_url': redirect_url})

@login_required
def update_post(request, post_id):
    post = get_object_or_404(Post, id=post_id)
    if post.owner != request.user:
        return redirect('users:article_list')
    
    if request.method == 'POST':
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            form.save()
            return redirect('users:article_list')
    else:
        form = PostForm(instance=post)
    
    return render(request, 'users/edit_post.html', {'form': form, 'post': post})


@login_required
def article_list(request):
    posts = Post.objects.filter(owner=request.user)  # 查询当前用户的文章
    return render(request, 'users/article_list.html', {'posts': posts})


